using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace IppServer.Host.Configuration
{
    /// <summary>
    /// 管理员密码初始化管理器
    /// 用于防止通过删除配置文件绕过认证
    /// </summary>
    internal static class AdminPasswordInitializer
    {
        private const string InitTokenFileName = ".admin_init_token";
        private static readonly string InitTokenPath;

        static AdminPasswordInitializer()
        {
            var configPath = AppSettingsStore.GetPath();
            var configDir = Path.GetDirectoryName(configPath);
            InitTokenPath = Path.Combine(configDir ?? AppDomain.CurrentDomain.BaseDirectory, InitTokenFileName);
        }

        /// <summary>
        /// 检查是否已初始化（存在初始化令牌）
        /// </summary>
        public static bool IsInitialized()
        {
            try
            {
                return File.Exists(InitTokenPath);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 创建初始化令牌（仅允许通过GUI调用）
        /// </summary>
        public static bool CreateInitToken()
        {
            try
            {
                var token = GenerateInitToken();
                File.WriteAllText(InitTokenPath, token, Encoding.UTF8);
                // 设置文件为隐藏和只读，增加安全性
                try
                {
                    var fileInfo = new FileInfo(InitTokenPath);
                    fileInfo.Attributes |= FileAttributes.Hidden | FileAttributes.ReadOnly;
                }
                catch
                {
                    // 如果设置属性失败，忽略（某些系统可能不支持）
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 验证初始化令牌
        /// </summary>
        public static bool ValidateInitToken(string token)
        {
            try
            {
                if (!File.Exists(InitTokenPath))
                {
                    return false;
                }

                var storedToken = File.ReadAllText(InitTokenPath, Encoding.UTF8).Trim();
                return string.Equals(storedToken, token, StringComparison.Ordinal);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 删除初始化令牌（密码设置成功后调用）
        /// </summary>
        public static bool RemoveInitToken()
        {
            try
            {
                if (File.Exists(InitTokenPath))
                {
                    // 先移除只读属性
                    try
                    {
                        var fileInfo = new FileInfo(InitTokenPath);
                        fileInfo.Attributes &= ~FileAttributes.ReadOnly;
                    }
                    catch
                    {
                        // 忽略
                    }
                    File.Delete(InitTokenPath);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 生成初始化令牌（基于机器特征和随机数）
        /// </summary>
        private static string GenerateInitToken()
        {
            try
            {
                // 使用机器名、用户名和随机数生成令牌
                var machineName = Environment.MachineName;
                var userName = Environment.UserName;
                var randomBytes = new byte[32];
                using (var rng = RandomNumberGenerator.Create())
                {
                    rng.GetBytes(randomBytes);
                }

                var input = $"{machineName}:{userName}:{Convert.ToBase64String(randomBytes)}";
                using (var sha256 = SHA256.Create())
                {
                    var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
                    return Convert.ToBase64String(hash);
                }
            }
            catch
            {
                // 如果生成失败，使用简单的随机字符串
                var randomBytes = new byte[32];
                using (var rng = RandomNumberGenerator.Create())
                {
                    rng.GetBytes(randomBytes);
                }
                return Convert.ToBase64String(randomBytes);
            }
        }

        /// <summary>
        /// 获取初始化令牌（用于GUI显示）
        /// </summary>
        public static string GetInitToken()
        {
            try
            {
                if (File.Exists(InitTokenPath))
                {
                    return File.ReadAllText(InitTokenPath, Encoding.UTF8).Trim();
                }
            }
            catch
            {
                // 忽略错误
            }
            return null;
        }
    }
}

